package com.sun.config;

import com.sun.pojo.User;
import com.sun.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author sun
 * @date 2021/2/20 - 9:42
 */
//自定义的UserRealm  继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权---doGetAuthorizationInfo");
        //
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


        //拿到当前这个对象
        Subject subject = SecurityUtils.getSubject();
        User user  = (User) subject.getPrincipal();//拿到当前用户

        //设置当前用户权限
        info.addStringPermission(user.getPerms());
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证---doGetAuthenticationInfo");
        //缓存取用户名密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        //用户名密码 数据库中取
        User user = userService.queryUserByName(usernamePasswordToken.getUsername());
        if (null==user) {
            return null;//抛出异常UnknownAccountException
        }

        //密码认证shiro做
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
